import 'package:baseProjectFlutter/utils/http/http_error.dart';
import 'package:baseProjectFlutter/widgets_common/dialog/base/app_toast.dart';
import 'package:baseProjectFlutter/widgets_common/dialog/base/loading_dialog.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';

import '../../base/mvvm/base_view_model.dart';
import '../../widgets_common/load_switch/load_switch.dart';
import '../../widgets_common/refresh/app_refresh_controller.dart';

class HttpUiHandle {
  BuildContext? context;
  bool isCompleted = false;

  //是否错误的时候toast提示,只有Http错误的时候
  bool isErrorToastShow = true;

  //是否显示对话框
  bool isShowLoadding = true;

  //对话框是否可以取消
  bool isCancelable = true;

  //对话框提示的文本
  String hint = "";

  //刷新和分页控制器
  AppRefreshController? refreshController;

  //布局切换的控制器
  LoadStateController? loadStateController;

  HttpUiHandle.get(
    BaseViewModel viewModel, {
    this.refreshController,
    this.loadStateController,
    this.isErrorToastShow = true,
  }) {
    context = viewModel.context;
    refreshController = refreshController ?? viewModel.refreshController;
    loadStateController = loadStateController ?? viewModel.loadStateController;
  }

  /// 显示Toast
  void showErrorToast(String msg) {
    if (isErrorToastShow) {
      msg.toastInfo();
    }
  }

  //是否正在刷新或者加载更多数据
  bool isRefreshOrLoadMore() => refreshController?.isRefresh == true || refreshController!.isLoadMore == true;

  //是否布局切换正在加载
  bool isPageLoading() => loadStateController?.isLoading() == true;

  /// 显示 Loading 框
  void showLoadDialog() {
    if (!isRefreshOrLoadMore() && !isPageLoading()) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!isRefreshOrLoadMore() && !isPageLoading() && !isCompleted) {
          hideLoadingDialog();
          showLoadingDialog(msg: hint);
        }
      });
    }
  }

  void start() {
    isCompleted = false;
    if (loadStateController?.isBind() == true) {
      loadStateController?.showLoading();
    } else {
      showLoadDialog();
    }
  }

  void error(e) {
    showErrorToast(HttpError.getError(e));
    refreshController?.finishRefresh(IndicatorResult.fail);
    refreshController?.finishLoad(IndicatorResult.fail);
  }

  void completed() {
    isCompleted = true;
    hideLoadingDialog();
  }

  void success(result) {
    refreshController?.finishRefresh(IndicatorResult.success);
    refreshController?.finishLoad(IndicatorResult.success);
    loadStateController?.showContent();
  }
}
